import { Component, OnInit } from '@angular/core';
import { ConfirmationService, MessageService } from 'primeng/api';
import { TaskService } from 'src/app/service/task.service';

@Component({
    selector: 'app-task-manage',
    templateUrl: './task-manage.component.html',
    styleUrls: ['./task-manage.component.scss'],
    providers: [ConfirmationService, MessageService],
})
export class TaskManageComponent implements OnInit {
    editTag: boolean;
    display: boolean = false;
    data: any[];
    display1: boolean = false;
    currentItem = { id: null };
    cronForm = {
        cron: '',
    };
    status: any = [
        { label: '结束', value: '0' },
        { label: '运行', value: '1' },
    ];
    addForm = {
        id: '',
        beanClass: '',
        createTime: '',
        createUser: '',
        cronExpression: '',
        jobDescription: '',
        jobGroup: '',
        jobName: '',
        jobStatus: null,
        updateTime: '',
        updateUser: '',
    };
    blankForm = {
        id: '',
        beanClass: '',
        createTime: '',
        createUser: '',
        cronExpression: '',
        jobDescription: '',
        jobGroup: '',
        jobName: '',
        jobStatus: null,
        updateTime: '',
        updateUser: '',
    };
    constructor(
        private confirmationService: ConfirmationService,
        private messageService: MessageService,
        private taskService: TaskService
    ) {}
    genTwoLengthNumberString = (n) => (n >= 10 ? n : '0' + n);
    dateTimeTrans(d) {
        if (!d) {
            return '';
        }
        if (typeof d === 'string') {
            return d;
        }
        let yy = d.getFullYear();
        let MM = this.genTwoLengthNumberString(d.getMonth() + 1);
        let dd = this.genTwoLengthNumberString(d.getDate());
        let hh = this.genTwoLengthNumberString(d.getHours());
        let mm = this.genTwoLengthNumberString(d.getMinutes());
        let ss = this.genTwoLengthNumberString(d.getSeconds());
        return yy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss;
    }
    async fetchTask() {
        const res = await this.taskService.fetchTaskByNone();
        this.data = res;
        console.log(res);
    }
    submit(){
        if(this.editTag===true){
            this.edit()
            this.display = false
            this.fetchTask();
        }else{
            this.add()
            this.display = false
            this.fetchTask();
        }
    }
    async add() {
        const res = await this.taskService.addTaskByConfig({
            ...this.addForm,
            createTime: this.dateTimeTrans(this.addForm.createTime),
            updateTime: this.dateTimeTrans(this.addForm.updateTime),
        });
        if (res.code == 200) {
            this.display = false;
        }
    }
    async editCron() {
        const res = await this.taskService.editTaskCronById({
            jobId: this.currentItem.id,
            cronExpression: this.cronForm.cron,
        });
        if (res.code == 200) {
            this.fetchTask();
            this.display1 = false
            return true;
        }
        return false;
    }
    async changeState(item) {
        console.log('occcc', item);
        let res;
        if (item.jobStatus == 0) {
            res = await this.taskService.editTaskStatusById({
                id: item.id,
                jobStatus: '1',
            });
        }
        if (item.jobStatus == 1) {
            res = await this.taskService.editTaskStatusById({
                id: item.id,
                jobStatus: '0',
            });
        }
        if (res && res.code == 200) {
            this.fetchTask();
            return true;
        }
        return false;
    }
    async edit() {
        console.log({
            ...this.addForm,
            createTime: this.dateTimeTrans(this.addForm.createTime),
            updateTime: this.dateTimeTrans(this.addForm.updateTime),
        })
        const res = await this.taskService.editTaskByConfig({
            ...this.addForm,
            createTime: this.dateTimeTrans(this.addForm.createTime),
            updateTime: this.dateTimeTrans(this.addForm.updateTime),
            id: this.currentItem.id,
        });
        console.log(res)
        if (res.code == 200) {
            this.fetchTask();
            this.display = false;
        }else if(res.code == -1){
            this.messageService.add({
                severity: 'error',
                summary: '警告',
                detail: '操作失败',
            });
        }
    }
    async delete() {
        const res = await this.taskService.deleteTaskById({
            id: this.currentItem.id,
        });
        console.log(res)
        if (res.code == 200) {
            this.fetchTask();
            this.messageService.add({
                severity: 'info',
                summary: '确认',
                detail: '你已经删除',
            });
        }else if(res.code==-1){
            this.messageService.add({
                severity: 'error',
                summary: '警告',
                detail: '删除前先停止任务',
            });
        }
    }
    openDialog() {
        this.editTag = false
        this.display = true;
        this.addForm = {
            ...this.blankForm
        }
    }
    openDialog2(item) {
        this.editTag = true
        let a = new Date(item.createTime)
        let b = new Date(item.updateTime)
        this.display = true;
        this.addForm = {
            ...item,
            createTime:a,
            updateTime:b
        }
    }
    openDialog1(item) {
        this.display1 = true;
        this.cronForm.cron = item.cronExpression;
        this.currentItem.id = item.id;
    }
    ngOnInit(): void {
        this.fetchTask();
    }
    deleteTask(item: any) {
        //console.log("ok")
        this.currentItem.id = item.id
        console.log(this.currentItem.id)
        this.confirmationService.confirm({
            message: '请问你确认删除吗 ?',
            header: '警告',
            icon: 'pi pi-exclamation-triangle',
            accept: () => {
                this.delete()
            },
        });
    }
}
